package firewing.servlet;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;

import firewing.datastore.TrendStore;
import firewing.object.Trend;
import firewing.service.google.GoogleTrendsExtractor;

public class GoogleTrendsTask extends HttpServlet {
	private static final long serialVersionUID = 5116647760208894339L;

	private static final Logger log = Logger.getLogger(GoogleTrendsTask.class
			.getName());

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doExecute(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doExecute(req, resp);
	}

	protected void doExecute(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		for (Trend t : GoogleTrendsExtractor.run()) {
			TrendStore.put(t);
		}
	}

	public static void createTask() {
		log.info("Creating google trends task");

		try {
			Queue queue = QueueFactory.getQueue("trends-queue");
			queue.add(TaskOptions.Builder.withUrl("/GoogleTrendsTask"));
			log.info("Create google trends task finished");
		} catch (Exception e) {
			e.printStackTrace();
			log.severe("Create google trends task failed");
		}
	}
}
